package com.cart.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    // MySQL 数据库的连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/cartManager";
    private static final String USER = "root";
    private static final String PASSWORD = "xfn123";

    // 序列化对象列表到MySQL数据库
    public static <T> void writeToFile(String filename, List<T> list) {
        if (list == null || list.isEmpty()) {
            System.out.println("对象列表为空，未写入文件。");
            return;
        }

        T firstObject = list.get(0);
        Field[] fields = firstObject.getClass().getDeclaredFields();

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            // 动态生成SQL创建表的语句（基于对象的字段名）
            StringBuilder createTableQuery = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
            createTableQuery.append(filename).append(" (id INT PRIMARY KEY AUTO_INCREMENT");

            for (Field field : fields) {
                field.setAccessible(true);
                createTableQuery.append(", ").append(field.getName()).append(" VARCHAR(255)");
            }
            createTableQuery.append(");");

            // 执行创建表的SQL语句
            try (Statement stmt = conn.createStatement()) {
                stmt.execute(createTableQuery.toString());
            }

            // 插入数据
            StringBuilder insertQuery = new StringBuilder("INSERT INTO ");
            insertQuery.append(filename).append(" (");
            for (Field field : fields) {
                insertQuery.append(field.getName()).append(", ");
            }
            insertQuery.delete(insertQuery.length() - 2, insertQuery.length());
            insertQuery.append(") VALUES (");
            for (int i = 0; i < fields.length; i++) {
                insertQuery.append("?, ");
            }
            insertQuery.delete(insertQuery.length() - 2, insertQuery.length());
            insertQuery.append(")");

            // 准备插入语句并插入每个对象
            try (PreparedStatement pstmt = conn.prepareStatement(insertQuery.toString())) {
                for (T obj : list) {
                    for (int i = 0; i < fields.length; i++) {
                        fields[i].setAccessible(true);
                        Object value = fields[i].get(obj);
                        pstmt.setString(i + 1, value != null ? value.toString() : null);
                    }
                    pstmt.addBatch();
                }
                pstmt.executeBatch();
            }
        } catch (SQLException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 从MySQL数据库反序列化对象列表
    public static <T> List<T> readFromFile(String filename, Class<T> clazz) throws InvocationTargetException {
        List<T> list = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            String query = "SELECT * FROM " + filename;

            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(query)) {

                while (rs.next()) {
                    T obj = clazz.getDeclaredConstructor().newInstance();

                    for (int i = 0; i < fields.length; i++) {
                        fields[i].setAccessible(true);
                        String value = rs.getString(fields[i].getName());

                        if (fields[i].getType() == int.class) {
                            fields[i].setInt(obj, Integer.parseInt(value));
                        } else if (fields[i].getType() == double.class) {
                            fields[i].setDouble(obj, Double.parseDouble(value));
                        } else {
                            fields[i].set(obj, value);
                        }
                    }

                    list.add(obj);
                }
            }

        } catch (SQLException | IllegalAccessException | InstantiationException | NoSuchMethodException e) {
            e.printStackTrace();
        }

        return list;
    }
}
